//
//  ZYModifyUsernameVC.m
//  YiLin
//
//  Created by Zyark on 2018/5/31.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYModifyUsernameVC.h"
#import "ZYViewUtils.h"
#import "ZYModifyUserInfoViewModel.h"
#import "ZYUser.h"

@interface ZYModifyUsernameVC ()
@property(nonatomic,strong) UITextField *usernameField;
@property(nonatomic,strong) UIButton *confirmBtn;

/**
 修改用户信息
 */
@property(nonatomic,strong) ZYModifyUserInfoViewModel *viewModel;
@end

@implementation ZYModifyUsernameVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.title = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_ME_MAIN_MODIFY_USERNAME];
}

#pragma mark - init
-(void)setup{
    [self setupTap];//点击关闭键盘
    [self setupView];
}

-(void)setupView{
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    _usernameField = [ZYViewUtils setupTextFieldWithLeftTitle:[language getStringByKey:LC_ME_MAIN_MODIFY_USERNAME_LABEL] placeholder:[language getStringByKey:LC_ME_MAIN_MODIFY_USERNAME_PLACEHOLDER]];
    [self.view addSubview:_usernameField];
    _usernameField.top = self.navigationView.bottom;
    _usernameField.centerX = self.view.centerX;
    ZYUser *user = [ZYConfig userInfo];
    _usernameField.text = user.username;
    
    _confirmBtn = [ZYViewUtils setupConfirmBtn];
    [self.view addSubview:_confirmBtn];
    [_confirmBtn setTitle:[language getStringByKey:LC_ME_MAIN_MODIFY_BUTTON_TITLE] forState:UIControlStateNormal];
    _confirmBtn.centerX = self.view.centerX;
    _confirmBtn.top = _usernameField.bottom + 25;
    [_confirmBtn addTarget:self action:@selector(confirmModify:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark -Event
-(void)confirmModify:(id)button{
    [self dismissKeyboard];
    self.viewModel.nickname = _usernameField.text;
    @weakify(self);
    [[self.viewModel.nicknameModifyCommand execute:nil] subscribeNext:^(id x) {
        @strongify(self);
        [[ToastHelper sharedToastHelper] toastSuccess:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_MODIFY_USERNAME_SUCCESS]];
        [self.navigationController popViewControllerAnimated:YES];
    } error:^(NSError *error) {
        [ZYBasicHelper handleErrorMessaeWithError:error message:[NSErrorHelper handleErrorMessage:error] controller:self];
    }];
    //监听状态
    [[self.viewModel.nicknameModifyCommand.executing skip:1] subscribeNext:^(id x) {
        BOOL executing = [x boolValue];
        ((UIButton *)button).enabled = !executing;
        [[ToastHelper sharedToastHelper] setSimleProgressVisiable:executing];
    }];
}

#pragma mark - Getter
-(ZYModifyUserInfoViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[ZYModifyUserInfoViewModel alloc] init];
    }
    return _viewModel;
}

@end
